package com.guodi.model.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.common.exception.BaseRuntimeException;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.secure.LoginUser;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.model.dto.req.AvtReportIdtExcelReqDTO;
import com.guodi.model.entity.*;
import com.guodi.model.mapper.IdtReportValueMapper;
import com.guodi.model.service.*;
import com.guodi.model.utils.JudgeWarnRuleUtil;
import com.guodi.model.vo.ApiIndicatorsValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @描述：指标上报值表 服务类
 * @作者: 彭辉
 * @日期: 2020-06-05
 */
@Service
@Slf4j
public class IdtReportValueServiceImpl extends ServiceImpl<IdtReportValueMapper, IdtReportValue> implements IIdtReportValueService {

    @Resource
    private IdtReportValueMapper idtReportValueMapper;
    @Resource
    private IIdtTargetValueService iIdtTargetValueService;
    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;
    @Resource
    private IIdtIndicatorsService iIdtIndicatorsService;
    @Resource
    private IIdtWarnRuleService iIdtWarnRuleService;
    @Resource
    private IIdtYearRelevanceService iIdtYearRelevanceService;
    @Resource
    private IIdtIndicatorsDirService idtIndicatorsDirService;
    /**
     * 指标数值相关操作类，主要是针对上报值的新增和修改    <br/>
     * 如果需要增加业务操作，请自行继承IIdtValueOperation接口，并交给spring管理
     */
//    @Autowired
    private List<IIdtValueOperation<IdtReportValue>> iIdtValueOperationList;


    /**
     * 获取指标上报的所有年份值列表
     * @入参: idtTypeCode 指标体系编码
     * @入参: divisionCode 行政区划编码
     * @入参: orgId 组织单位id
     * @出参: 指标上报的所有年份值列表
     */
    @Override
    public List<Integer> listIdtReportYear( String idtTypeCode,  String divisionCode, String orgId, String idtTypeId){
        //获取指标列表
        List<ApiIdtIndicatorsDir> apiIdtIndicatorsDirs = idtIndicatorsDirService.listIdtDirForReport(idtTypeCode, orgId, null, null, null, divisionCode, idtTypeId);
        // 获取指标id列表
        List<String> idtIdList = apiIdtIndicatorsDirs.stream().filter(idtDir -> idtDir.getType() == 2).map(ApiIdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());
        if(idtIdList == null || idtIdList.isEmpty()){
            return new LinkedList<>();
        }
        // 上报年份范围
        QueryWrapper<IdtReportValue> queryWrapper1 = new QueryWrapper();
        queryWrapper1.select("distinct year");
        queryWrapper1.in("indicators_id", idtIdList);
        queryWrapper1.eq("division_code", divisionCode);
        queryWrapper1.orderByAsc("year");
        List<IdtReportValue> reportYearList = this.list(queryWrapper1);
        List<Integer> yearList = reportYearList.stream().map(IdtReportValue::getYear).collect(Collectors.toList());
        return yearList;
    }

    @Override
    public List<IdtReportValue> listByKeyWord(String keyWord, Integer year, long pageSize, long start, String sort, String sortWay, String divisionCode, String orgId) {
        return idtReportValueMapper.listByKeyWord(keyWord, year, pageSize,start,sort,sortWay,divisionCode,orgId);
    }

    @Override
    public Integer listByKeyWordCount(String keyWord,String orgId) {
        return idtReportValueMapper.listByKeyWordCount(keyWord,orgId);
    }

    @Override
    public Integer listByKeyWordAndCodeCount(String keyWord, Integer year, String divisionCode, String orgId) {
        return idtReportValueMapper.listByKeyWordAndCodeCount(keyWord,year,divisionCode,orgId);
    }

    @Override
    public String getNameByDivisionCode(String divisionCode) {
        return idtReportValueMapper.getNameByDivisionCode(divisionCode);
    }

    @Override
    public Integer isStandard(String indicatorsId, String year, String area,String reportValue) {
        Integer isStandard = 0;
        try {
            // 对应的规划值
            String targetValue = null;
            //查询对标关系
            IdtYearRelevance idtYearRelevance = queryYearRelevances(indicatorsId, year);
            //查询预警规则
            IdtWarnRule warnRule = iIdtWarnRuleService.listWarnRuleById(indicatorsId);
            String idtWarnRules = null;
            if(null != warnRule){
                idtWarnRules =  warnRule.getName();
            }

            LambdaQueryWrapper<IdtYearRelevance> lambda = new QueryWrapper().lambda();
            lambda.eq(IdtYearRelevance::getIndicatorsId,indicatorsId);
            //查询对应的规划值
            if(idtYearRelevance!=null){
                String monitorReportYear = idtYearRelevance.getMonitorReportYear();
                String[] split = monitorReportYear.split("-");
                if(split!=null && split.length==2){
                    int starYear = Integer.valueOf(split[0]);
                    int endYear = Integer.valueOf(split[1]);
                    int monitorYear = Integer.valueOf(year);
                    if(monitorYear>=starYear && monitorYear<=endYear){
                        //规划目标年
                        Integer planTargetYear = idtYearRelevance.getPlanTargetYear();
                        // 获取对应的规划值
                        LambdaQueryWrapper<IdtTargetValue> lambda3 = new QueryWrapper().lambda();
                        lambda3.eq(IdtTargetValue::getIndicatorsId,indicatorsId);
                        lambda3.eq(IdtTargetValue::getTargetYear,planTargetYear);
                        lambda3.eq(IdtTargetValue::getDivisionCode,area);
                        List<IdtTargetValue> list3 = iIdtTargetValueService.list(lambda3);
                        if(list3!=null && list3.size()>0){
                            IdtTargetValue idtTargetValue = list3.get(0);
                            //规划值
                            targetValue = idtTargetValue.getTargetValue();
                        }
                    }
                 }
            }
            if(StringUtils.isBlank(targetValue)){
                //规划值为空， 达标
                isStandard =1;
            } else if(StringUtils.isNotBlank(reportValue)){
                if( "反向".equals(idtWarnRules)){
                    if(Float.parseFloat(reportValue) <= Float.parseFloat(targetValue)){
                        isStandard =1;
                    }
                }else if( Float.parseFloat(reportValue) >= Float.parseFloat(targetValue)){
                    isStandard =1;
                }
            }
        }catch (Exception e){
             isStandard = 0;
        }
        return isStandard;
    }

    @Override
    public Integer isUnify(String indicatorsId, String year, String area,String reportValue) {
        try {
            String monitorValue = "";
            //查询监测值
            LambdaQueryWrapper<IdtMonitorValue> lambda1 = new QueryWrapper().lambda();
            lambda1.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
            lambda1.eq(IdtMonitorValue::getDivisionCode,area);
            lambda1.eq(IdtMonitorValue::getYear,Integer.valueOf(year));
            lambda1.orderByDesc(IdtMonitorValue::getMonitorTime);
            List<IdtMonitorValue> list = iIdtMonitorValueService.list(lambda1);
            if(list!=null && list.size()>0){
                IdtMonitorValue idtMonitorValue = list.get(0);
                monitorValue = idtMonitorValue.getMonitorValue();
            }
            if(StringUtils.isBlank(monitorValue) && StringUtils.isBlank(reportValue)){
                return 1;
            }
            if(StringUtils.isNotBlank(monitorValue) && StringUtils.isNotBlank(reportValue)){
                if(Float.parseFloat(monitorValue)==(Float.parseFloat(reportValue))){
                    return 1;
                }
            }
        }catch (Exception e){
            return 0;
        }
        return 0;
    }

    @Override
    public IdtYearRelevance queryYearRelevances(String indicatorsId, String year) {
        //查询对标关系
        LambdaQueryWrapper<IdtYearRelevance> lambda = new QueryWrapper().lambda();
        lambda.eq(IdtYearRelevance::getIndicatorsId,indicatorsId);
        IdtYearRelevance result = null;
        List<IdtYearRelevance> idtYearRelevances = iIdtYearRelevanceService.list(lambda);
        if(idtYearRelevances!=null && !idtYearRelevances.isEmpty()){
            for (int i = 0; i <idtYearRelevances.size() ; i++) {
                IdtYearRelevance idtYearRelevance = idtYearRelevances.get(i);
                String monitorReportYear = idtYearRelevance.getMonitorReportYear();
                String[] split = monitorReportYear.split("-");
                if(split!=null && split.length==2){
                    int starYear = Integer.valueOf(split[0]);
                    int endYear = Integer.valueOf(split[1]);
                    int monitorYear = Integer.valueOf(year);
                    if(monitorYear>=starYear && monitorYear<=endYear){
                        result = idtYearRelevance;
                    }

                }
            }
        }
        return result;
    }

    @Override
    public void updateUnify(String indicatorsId, String year, String area) {
        try {
            String monitorValue = null;
            IdtReportValue reportValue = null;
            //查询最新采集时间的监测值
            LambdaQueryWrapper<IdtMonitorValue> lambda0 = new QueryWrapper().lambda();
            lambda0.eq(IdtMonitorValue::getIndicatorsId, indicatorsId);
            lambda0.eq(IdtMonitorValue::getDivisionCode, area);
            lambda0.eq(IdtMonitorValue::getYear, Integer.valueOf(year));
            lambda0.orderByDesc(IdtMonitorValue::getMonitorTime);
            List<IdtMonitorValue> list = iIdtMonitorValueService.list(lambda0);
            if(list!=null&&list.size()>0){
                // 取最新采集时间的监测值
                monitorValue = list.get(0).getMonitorValue();
            }
            //查询对应年份的上报值
            LambdaQueryWrapper<IdtReportValue> lambda = new QueryWrapper().lambda();
            lambda.eq(IdtReportValue::getIndicatorsId, indicatorsId);
            lambda.eq(IdtReportValue::getDivisionCode, area);
            lambda.eq(IdtReportValue::getYear, Integer.valueOf(year));
            List<IdtReportValue> list2 = this.list(lambda);
            if(list2!=null&&list2.size()>0){
                // 取最新采集时间的监测值
                reportValue = list2.get(0);
            }
            if (reportValue != null) {
                if (StringUtils.isNotBlank(monitorValue)&&StringUtils.isNotBlank(reportValue.getValue()) && Float.parseFloat(monitorValue) == (Float.parseFloat(reportValue.getValue()))) {
                    //最新采集时间的监测值和上报值相等说明符合统一
                    reportValue.setIsUnify(1);
                } else {
                    //不相等不符合
                    reportValue.setIsUnify(0);
                }
                this.updateById(reportValue);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("更新统一率失败");
        }
    }

    @Override
    public void updateStandard(String indicatorsId, String area, String targetYear, String targetValue) {
        if(StringUtils.isBlank(indicatorsId)||StringUtils.isBlank(targetYear)){
            return;
        }
        //查询该规划目标年的对标关系
        LambdaQueryWrapper<IdtYearRelevance> lambda = new QueryWrapper().lambda();
        lambda.eq(IdtYearRelevance::getIndicatorsId,indicatorsId);
        lambda.eq(IdtYearRelevance::getPlanTargetYear,Integer.valueOf(targetYear));
        List<IdtYearRelevance> idtYearRelevances = iIdtYearRelevanceService.list(lambda);
        List<IdtReportValue> list = new ArrayList<>();
        if(idtYearRelevances!=null&&idtYearRelevances.size()>0){
            for (IdtYearRelevance idtYearRelevance: idtYearRelevances) {
                String monitorReportYear = idtYearRelevance.getMonitorReportYear();
                String[] split = monitorReportYear.split("-");
                if(split!=null && split.length==2){
                    int starYear = Integer.valueOf(split[0]);
                    int endYear = Integer.valueOf(split[1]);
                    //查询该规划目标年对应的所有上报值
                    LambdaQueryWrapper<IdtReportValue> lambda1 = new QueryWrapper().lambda();
                    lambda1.eq(IdtReportValue::getIndicatorsId, indicatorsId);
                    lambda1.eq(IdtReportValue::getDivisionCode, area);
                    lambda1.ge(IdtReportValue::getYear, starYear);
                    lambda1.le(IdtReportValue::getYear, endYear);
                    List<IdtReportValue> list1 = this.list(lambda1);
                    if(list1!=null){
                        list.addAll(list1);
                    }
                }
            }
        }
        if(list.size()>0){
            //查询预警规则
            IdtWarnRule warnRule = iIdtWarnRuleService.listWarnRuleById(indicatorsId);
            String idtWarnRules = null;
            if(null != warnRule){
                idtWarnRules =  warnRule.getName();
            }
            //判断是否达标
            for (IdtReportValue idtReportValue: list) {
                //未达标
                Integer isStandard = 0;
                String reportValue = idtReportValue.getValue();
                if (StringUtils.isBlank(idtWarnRules) || StringUtils.isBlank(targetValue) || StringUtils.isBlank(reportValue)) {
                    isStandard = null;
                } else {
                    if( "反向".equals(idtWarnRules)){
                        if(Float.parseFloat(reportValue) <= Float.parseFloat(targetValue)){
                            isStandard =1;
                        }
                    } else if( "正向".equals(idtWarnRules)) {
                        if( Float.parseFloat(reportValue) >= Float.parseFloat(targetValue)) {
                            isStandard = 1;
                        }
                    }
                }
                idtReportValue.setIsStandard(isStandard);
            }
            //批量更新规划目标年对应所有上报值的是否达标字段
            this.updateBatchById(list);
        }
    }

    /**
     * @描述: 根据指标ID和预警规则，更新监测值的预警状态、上报值的达标状态
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/2/1 16:01
     */
    @Override
    public void updateWarnStatusAndStandard(String indicatorsId, IdtWarnRule idtWarnRule) {
        //查询该规划目标年的对标关系
        LambdaQueryWrapper<IdtYearRelevance> relevancelambda = new QueryWrapper().lambda();
        relevancelambda.eq(IdtYearRelevance::getIndicatorsId,indicatorsId);
        List<IdtYearRelevance> idtYearRelevances = iIdtYearRelevanceService.list(relevancelambda);

        //查询指标对应监测值列表
        LambdaQueryWrapper<IdtMonitorValue> monitorLambda = new QueryWrapper().lambda();
        monitorLambda.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
        List<IdtMonitorValue> idtMonitorValues = iIdtMonitorValueService.list(monitorLambda);

        //查询指标对应上报值列表
        LambdaQueryWrapper<IdtReportValue> reportLambda = new QueryWrapper().lambda();
        reportLambda.eq(IdtReportValue::getIndicatorsId,indicatorsId);
        List<IdtReportValue> idtReportValues = this.list(reportLambda);

        //查询指标对应规划值列表
        LambdaQueryWrapper<IdtTargetValue> targetLambda = new QueryWrapper().lambda();
        targetLambda.eq(IdtTargetValue::getIndicatorsId,indicatorsId);
        List<IdtTargetValue> idtTargetValues = iIdtTargetValueService.list(targetLambda);


        if (idtMonitorValues != null && idtMonitorValues.size() > 0) {
            for (IdtMonitorValue monitorValue : idtMonitorValues) {
                String warnStatu = JudgeWarnRuleUtil.getWarnName(idtYearRelevances, idtTargetValues, idtWarnRule, monitorValue.getMonitorValue(), monitorValue.getYear(), monitorValue.getDivisionCode(), monitorValue.getIndicatorsId());
                monitorValue.setWarnStatus(warnStatu);
            }
            iIdtMonitorValueService.saveOrUpdateBatch(idtMonitorValues);
        }

        if (idtReportValues != null && idtReportValues.size() > 0) {
            for (IdtReportValue reportValue : idtReportValues) {
                String warnStatu = JudgeWarnRuleUtil.getWarnName(idtYearRelevances, idtTargetValues, idtWarnRule, reportValue.getValue(), reportValue.getYear(), reportValue.getDivisionCode(), reportValue.getIndicatorsId());
                Integer isStandard = JudgeWarnRuleUtil.getIsStandard(idtYearRelevances, idtTargetValues, idtWarnRule, reportValue.getValue(), reportValue.getYear(), reportValue.getDivisionCode(), reportValue.getIndicatorsId());
                reportValue.setIsStandard(isStandard);
                reportValue.setWarnStatus(warnStatu);
            }
            this.saveOrUpdateBatch(idtReportValues);
        }
    }

    @Override
    public List<IdtReportValue> getHistoryList(String indicatorsId, List<Integer> yearList, String divisionCode) {
        return idtReportValueMapper.getHistoryList(indicatorsId, yearList, divisionCode);
    }

    @Override
    public List<IdtReportValue> getNewestData(String indicatorsId) {
        QueryWrapper<IdtReportValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("indicators_id", indicatorsId);
        queryWrapper.orderByDesc("year");
        return this.list(queryWrapper);
    }

    @Override
    public List<ApiIndicatorsValue> listCurrentAssessmentData(Integer year, String divisionCode, List<String> indicatorsList) {
        return idtReportValueMapper.listCurrentAssessmentData(year, divisionCode, indicatorsList);
    }

    /**
     * @描述：根据指标编码、年份、行政区划代码查询因子值
     * @作者：汤厚韬
     * @日期：2021/1/25
     */
    @Override
    public List<IdtReportValue> listByIndicatorsIds(List<String> calculateFactorNameList, Integer time, String divisionCode) {
        return idtReportValueMapper.listByIndicatorsIds(calculateFactorNameList, time, divisionCode);
    }

//    @Override
//    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
//    public void batchUpdateByAvtIndicatorsReportValues(List<AvtIndicatorsReportValue> avtIndicatorsReportValues, boolean coverIdt) {
//        if(CollectionUtils.isEmpty(avtIndicatorsReportValues)){
//            return;
//        }
//
//        BladeUser currentUser = AuthUtil.getUser();
//        String deptId = Objects.isNull(currentUser) ? "" : currentUser.getDeptId();
//        // 存储新增、更新指标集合
//        String indicatorsIds = "";
//        List<IdtReportValue> saveUpdateList = new ArrayList<>();
//        for (int i = 0; i < avtIndicatorsReportValues.size(); i++) {
//            AvtIndicatorsReportValue avtIndicatorsReportValue = avtIndicatorsReportValues.get(i);
//            String indicatorsId = avtIndicatorsReportValue.getIndicatorsId();
//            int year = Integer.parseInt(avtIndicatorsReportValue.getYear());
//            String divisionCode = avtIndicatorsReportValue.getDivisionCode();
//            String value = avtIndicatorsReportValue.getValue();
//            log.info("----------- avtIndicatorsReportValue = {}, value = {}", avtIndicatorsReportValue, value);
//
//            IdtReportValue idtReportValue = new IdtReportValue();
//            // 判断是否存在相同指标id与行政区划编码与相同年份 fixme: 避免循环查表
//            LambdaQueryWrapper<IdtReportValue> queryWrapper1 = new QueryWrapper().lambda();
//            queryWrapper1.eq(IdtReportValue::getYear, year);
//            queryWrapper1.eq(IdtReportValue::getDivisionCode, divisionCode);
//            queryWrapper1.eq(IdtReportValue::getIndicatorsId, indicatorsId);
//            List<IdtReportValue> sourceIdtReportValueList = list(queryWrapper1);
//            if(sourceIdtReportValueList.size() > 0){
//                // todo: 存在, 不覆盖, 跳过
//                if(!coverIdt){
//                    continue;
//                }
//                idtReportValue = sourceIdtReportValueList.get(0);
//            }
//
//            idtReportValue.setIndicatorsId(indicatorsId);
//            idtReportValue.setYear(year);
//            idtReportValue.setDivisionCode(divisionCode);
//            idtReportValue.setValue(value);
//            idtReportValue.setExplain("体检评估>成果上报审批成功后自动更新");
//            idtReportValue.setOrgId(deptId);
//            if(StringUtils.isBlank(idtReportValue.getId())){
//                prepareData(idtReportValue,true);
//                idtReportValue.setId(UuidUtil.get32UUID());
//            } else {
//                prepareData(idtReportValue,false);
//            }
//
//            // 判断是否统一
//            Integer unify = isUnify(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
//            idtReportValue.setIsUnify(unify);
//            // 判断是否达标
//            Integer standard = isStandard(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
//            idtReportValue.setIsStandard(standard);
//
//            // 存储需要更新的指标
//            saveUpdateList.add(idtReportValue);
//            indicatorsIds += indicatorsId;
//            indicatorsIds += ",";
//        }
//        if (saveUpdateList.size() > 0) {
//            // 批量保存更新
//            saveOrUpdateBatch(saveUpdateList);
//            // 更新指标表中的更新状态
//            iIdtIndicatorsService.updateReportStatus(indicatorsIds.substring(0, indicatorsIds.length() - 1));
//        }
//    }

    @Override
    public void batchUpdateByAvtReportIdtExcelReqDTOs(List<AvtReportIdtExcelReqDTO> avtReportIdtExcelReqDTOs, boolean coverIdt) {
        if(CollectionUtils.isEmpty(avtReportIdtExcelReqDTOs)){
            return;
        }

        String deptId = AuthUtil.getUser().getDeptId();
        // 存储新增、更新指标集合
        String indicatorsIds = "";
        List<IdtReportValue> saveUpdateList = new ArrayList<>();
        for (int i = 0; i < avtReportIdtExcelReqDTOs.size(); i++) {
            AvtReportIdtExcelReqDTO excelReqDTO = avtReportIdtExcelReqDTOs.get(i);
            String indicatorsId = excelReqDTO.getIndicatorsId();
            if(org.apache.commons.lang3.StringUtils.isBlank(indicatorsId)){
                continue;
            }
            int year = Integer.parseInt(excelReqDTO.getYear());
            String divisionCode = excelReqDTO.getDivisionCode();
            String value = excelReqDTO.getValue();
            //log.info("----------- excelReqDTO = {}, value = {}", excelReqDTO, value);

            IdtReportValue idtReportValue = new IdtReportValue();
            // 判断是否存在相同指标id与行政区划编码与相同年份 fixme: 循环查表, 可以在外层通过组装成map来实现
            LambdaQueryWrapper<IdtReportValue> queryWrapper1 = new QueryWrapper().lambda();
            queryWrapper1.eq(IdtReportValue::getYear, year);
            queryWrapper1.eq(IdtReportValue::getDivisionCode, divisionCode);
            queryWrapper1.eq(IdtReportValue::getIndicatorsId, indicatorsId);
            List<IdtReportValue> sourceIdtReportValueList = list(queryWrapper1);
            if(sourceIdtReportValueList.size() > 0){
                // todo: 存在数据, 不覆盖, 跳过
                if(!coverIdt){
                    continue;
                }
                idtReportValue = sourceIdtReportValueList.get(0);
            }

            idtReportValue.setIndicatorsId(indicatorsId);
            idtReportValue.setYear(year);
            idtReportValue.setDivisionCode(divisionCode);
            idtReportValue.setValue(value);
            idtReportValue.setExplain("体检评估>上传成果后自动更新");
            idtReportValue.setOrgId(deptId);
            if(StringUtils.isBlank(idtReportValue.getId())){
                prepareData(idtReportValue,true);
                idtReportValue.setId(UuidUtil.get32UUID());
            } else {
                prepareData(idtReportValue,false);
            }

            // 判断是否统一
            Integer unify = isUnify(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
            idtReportValue.setIsUnify(unify);
            // 判断是否达标
            Integer standard = isStandard(idtReportValue.getIndicatorsId(), idtReportValue.getYear() + "", idtReportValue.getDivisionCode(), idtReportValue.getValue());
            idtReportValue.setIsStandard(standard);

            // 存储需要更新的指标
            saveUpdateList.add(idtReportValue);
            indicatorsIds += indicatorsId;
            indicatorsIds += ",";
        }
        if (saveUpdateList.size() > 0) {
            // 批量保存更新
            saveOrUpdateBatch(saveUpdateList);
            // 更新指标表中的更新状态
            iIdtIndicatorsService.updateReportStatus(indicatorsIds.substring(0, indicatorsIds.length() - 1));
        }
    }

    @Override
    public Boolean checkIdtExistsByAvtReportIdtExcelReqDTOs(List<AvtReportIdtExcelReqDTO> avtReportIdtExcelReqDTOs) {
        if(CollectionUtils.isEmpty(avtReportIdtExcelReqDTOs)){
            return false;
        }

        for (int i = 0; i < avtReportIdtExcelReqDTOs.size(); i++) {
            AvtReportIdtExcelReqDTO excelReqDTO = avtReportIdtExcelReqDTOs.get(i);
            String indicatorsId = excelReqDTO.getIndicatorsId();
            if (org.apache.commons.lang3.StringUtils.isBlank(indicatorsId)) {
                continue;
            }
            int year = Integer.parseInt(excelReqDTO.getYear());
            String divisionCode = excelReqDTO.getDivisionCode();

            // 判断是否存在相同指标id与行政区划编码与相同年份 fixme: 循环查表, 可以在外层通过组装成map来实现
            LambdaQueryWrapper<IdtReportValue> condition = new QueryWrapper().lambda();
            condition.select(IdtReportValue::getId);
            condition.eq(IdtReportValue::getYear, year);
            condition.eq(IdtReportValue::getDivisionCode, divisionCode);
            condition.eq(IdtReportValue::getIndicatorsId, indicatorsId);
            List<IdtReportValue> entities = list(condition);
            if(!CollectionUtils.isEmpty(entities)){
                return true;
            }
        }

        return false;
    }

//    @Override
//    public Boolean checkIdtExistsByAvtIndicatorsReportValues(List<AvtIndicatorsReportValue> avtIndicatorsReportValues) {
//        if(CollectionUtils.isEmpty(avtIndicatorsReportValues)){
//            return false;
//        }
//
//        for (int i = 0; i < avtIndicatorsReportValues.size(); i++) {
//            AvtIndicatorsReportValue avtIndicatorsReportValue = avtIndicatorsReportValues.get(i);
//            String indicatorsId = avtIndicatorsReportValue.getIndicatorsId();
//            int year = Integer.parseInt(avtIndicatorsReportValue.getYear());
//            String divisionCode = avtIndicatorsReportValue.getDivisionCode();
//
//            // 判断是否存在相同指标id与行政区划编码与相同年份 fixme: 避免循环查表
//            LambdaQueryWrapper<IdtReportValue> condition = new QueryWrapper().lambda();
//            condition.select(IdtReportValue::getId);
//            condition.eq(IdtReportValue::getYear, year);
//            condition.eq(IdtReportValue::getDivisionCode, divisionCode);
//            condition.eq(IdtReportValue::getIndicatorsId, indicatorsId);
//            List<IdtReportValue> entities = list(condition);
//            if (!CollectionUtils.isEmpty(entities)) {
//                return true;
//            }
//        }
//
//        return false;
//    }

    private void prepareData(IdtReportValue idtReportValue, boolean isSave) {
        LoginUser currentUser = AuthUtil.getUser();
        String userId = Objects.isNull(currentUser) ? "" : String.valueOf(currentUser.getUserId());
        Date current = new Date();
        if(isSave){
            idtReportValue.setCreator(userId);
            idtReportValue.setCreateTime(current);
            idtReportValue.setModifier(userId);
            idtReportValue.setModifyTime(current);
        }else{
            idtReportValue.setModifier(userId);
            idtReportValue.setModifyTime(current);
        }
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(IdtReportValue entity) {
        entity.setCreateTime(new Date());
        try {
            entity.setCreator(AuthUtil.getUserId().toString());
        }catch (NullPointerException exception){
            // 避免获取不到userId而报错
        }
        entity.setModifyTime(null);
        entity.setModifier(null);

        // 上锁，避免进行业务操作时，其他人修改了最新的值
        synchronized (IdtReportValueServiceImpl.class){
            // 调用父类，执行简单保存
            boolean save = super.save(entity);
            // 执行额外的业务操作，如果需要增加业务操作，请自行继承IIdtValueOperation接口，并交给spring管理
            if (!CollectionUtils.isEmpty(this.iIdtValueOperationList)){
                for(IIdtValueOperation<IdtReportValue> idtReportValueIIdtValueOperation : this.iIdtValueOperationList) {
                    idtReportValueIIdtValueOperation.save(entity);
                }
            }
            return save;
        }
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(IdtReportValue entity) {
        entity.setModifyTime(new Date());
        try {
            entity.setModifier(AuthUtil.getUserId().toString());
        }catch (NullPointerException exception){
            // 避免获取不到userId而报错
        }
        entity.setCreateTime(null);
        entity.setCreator(null);

        // 上锁，避免进行业务操作时，其他人修改了最新的值
        synchronized (IdtReportValueServiceImpl.class){
            // 调用父类，执行简单更新
            boolean update = super.updateById(entity);
            // 执行额外的业务操作，如果需要增加业务操作，请自行继承IIdtValueOperation接口，并交给spring管理
            if (!CollectionUtils.isEmpty(this.iIdtValueOperationList)){
                for(IIdtValueOperation<IdtReportValue> idtReportValueIIdtValueOperation : this.iIdtValueOperationList) {
                    idtReportValueIIdtValueOperation.update(entity);
                }
            }
            return update;
        }
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveOrUpdate(IdtReportValue entity) {
        boolean b = this.saveOrUpdateBatch(Arrays.asList(entity));
        return b;
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveBatch(Collection<IdtReportValue> entityList) {
        boolean save = true;
        for(IdtReportValue idtReportValue : entityList) {
            save = save & this.save(idtReportValue);
        }
        return save;
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveOrUpdateBatch(Collection<IdtReportValue> entityList) {
        boolean update = true;
        for(IdtReportValue idtReportValue : entityList) {
            if (StringUtils.isBlank(idtReportValue.getId())){
                update = update & this.save(idtReportValue);
            }else{
                IdtReportValue byId = this.getById(idtReportValue.getId());
                if (byId == null){
                    update = update & this.save(idtReportValue);
                }else{
                    update = update & this.updateById(idtReportValue);
                }
            }
        }
        return update;
    }

    /**
     * （重写mybatis的保存方法）增加统一的额外操作    <br/><br/>
     * 所有更新评估值的都只能走这些接口
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean updateBatchById(Collection<IdtReportValue> entityList) {
        boolean update = true;
        for(IdtReportValue idtReportValue : entityList) {
            update = update & this.updateById(idtReportValue);
        }
        return update;
    }

    /**
     * 此方法禁用，saveBatch(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveBatch(Collection<IdtReportValue> entityList, int batchSize) {
        throw new RuntimeException("此方法禁用，saveBatch(Collection<IdtReportValue>)");
    }

    /**
     * 此方法禁用，请使用 saveOrUpdateBatch(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveOrUpdateBatch(Collection<IdtReportValue> entityList, int batchSize) {
        throw new RuntimeException("此方法禁用，请使用 saveOrUpdateBatch(Collection<IdtReportValue>)");
    }
    /**
     * 此方法禁用，请使用 updateBatchById(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean updateBatchById(Collection<IdtReportValue> entityList, int batchSize) {
        throw new RuntimeException("此方法禁用，请使用 updateBatchById(Collection<IdtReportValue> )");
    }

    /**
     * 此方法禁用，请使用 updateById(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean update(Wrapper<IdtReportValue> updateWrapper) {
        throw new RuntimeException("此方法禁用，请使用 updateById(IdtReportValue)");
    }

    /**
     * 此方法禁用，请使用 updateById(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean update(IdtReportValue entity, Wrapper<IdtReportValue> updateWrapper) {
        throw new RuntimeException("此方法禁用，请使用 updateById(IdtReportValue)");
    }

    /**
     * 此方法禁用，请使用 updateById(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public UpdateChainWrapper<IdtReportValue> update() {
        throw new RuntimeException("此方法禁用，请使用 updateById(IdtReportValue)");
    }

    /**
     * 此方法禁用，请使用 updateById(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public LambdaUpdateChainWrapper<IdtReportValue> lambdaUpdate() {
        throw new RuntimeException("此方法禁用，请使用 updateById(IdtReportValue)");
    }

    /**
     * 此方法禁用，请使用 saveOrUpdate(IdtReportValue)
     * @author 陈宏成
     * @date 2021-12-22
     */
    @Override
    public boolean saveOrUpdate(IdtReportValue entity, Wrapper<IdtReportValue> updateWrapper) {
        throw new RuntimeException("此方法禁用，请使用 saveOrUpdate(IdtReportValue)");
    }

    /**
     * 计算指标预警状态
     * @param indicatorsId 指标id
     * @param reportValue 评估值
     * @param year 上报年份
     * @param divisionCode 行政区划编码
     * @return 预警状态，例如：预警
     * @author 陈宏成
     * @date 2021-12-30
     */
    @Override
    public String getWarnStatus(String indicatorsId, String reportValue, String year, String divisionCode) {
        String warnStatu = null;
        // 获取指标对标关系
        IdtYearRelevance idtYearRelevance = this.queryYearRelevances(indicatorsId, year);
        if(idtYearRelevance==null){
            throw new BaseRuntimeException("未配置指标对标关系");
        }
        //获取预警规则
        IdtWarnRule warnRule = iIdtWarnRuleService.listWarnRuleById(indicatorsId);
        //查询规划值
        LambdaQueryWrapper<IdtTargetValue> lambda = new QueryWrapper().lambda();
        lambda.eq(IdtTargetValue::getIndicatorsId,indicatorsId);
        lambda.eq(IdtTargetValue::getTargetYear,idtYearRelevance.getPlanTargetYear());
        lambda.eq(IdtTargetValue::getDivisionCode,divisionCode);
        List<IdtTargetValue> list = iIdtTargetValueService.list(lambda);
        //规划值
        String targetValue = null;
        if(!CollectionUtils.isEmpty(list)){
            targetValue = list.get(0).getTargetValue();
        }
        if(targetValue == null || warnRule == null){
            return warnStatu;
        }
        if("正向".equals(warnRule.getName())){
            if(Float.parseFloat(reportValue)>Float.parseFloat(targetValue)){
                warnStatu = "正常";
            }else {
                warnStatu = "预警";
            }
        }else  if("反向".equals(warnRule.getName())){
            if(Float.parseFloat(reportValue)<Float.parseFloat(targetValue)){
                warnStatu = "正常";
            }else {
                warnStatu = "预警";
            }
        }
        return warnStatu;
    }
}
